package com.neuronbit.businessflow.intellij.function;

import com.neuronbit.businessflow.intellij.editor.BpmHtmlFileEditor;
import com.neuronbit.businessflow.intellij.dialog.Chooser;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.ui.jcef.JBCefJSQuery;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import org.apache.commons.lang3.StringUtils;
import org.cef.browser.CefBrowser;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.util.function.Function;

/**
 * The type Method filter function.
 */
public class MethodFilterFunction implements Function<String, JBCefJSQuery.Response> {
    private final Project project;
    private final CefBrowser cefBrowser;
    private final String viewerUrl;

    /**
     * Instantiates a new Method filter function.
     *
     * @param project    the project
     * @param cefBrowser the cef browser
     * @param viewerUrl  the viewer url
     */
    public MethodFilterFunction(Project project, @NotNull CefBrowser cefBrowser, String viewerUrl) {
        this.project = project;
        this.cefBrowser = cefBrowser;
        this.viewerUrl = viewerUrl;
    }

    @Override
    public JBCefJSQuery.Response apply(String params) { // 2
        Logger.getInstance(BpmHtmlFileEditor.class).info("message from browser " + params);
        String returnTypeFilter = null;
        String fieldId = null;
        if (StringUtils.isNotBlank(params)) {
            try {
                returnTypeFilter = JsonPath.read(params, "$.returnType");
            } catch (PathNotFoundException e) {
                //ignore
            }
            try {
                fieldId = JsonPath.read(params, "$.fieldId");
            } catch (PathNotFoundException e) {
                //ignore
            }
        }
//        GlobalSearchScope scope = GlobalSearchScope.allScope(project);
//        PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass(params, scope);
        EventQueue.invokeLater(new Chooser(project, returnTypeFilter, cefBrowser, fieldId, viewerUrl));
        return null;
//
//        PsiClass psiClass = selectedPsiClass[0];
//        if (null != psiClass) {
//            return new JBCefJSQuery.Response(psiClass.getQualifiedName(), 0, "success"); // 3
//        }
//
//
//        return new JBCefJSQuery.Response("xyz", 0, "success"); // 3
    }
}
